package com.example.train_operate.util;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.UUID;

public class OssUpload {

    /**
     * 上传文件到阿里云
     * @param file
     * @return
     */
    public static Result uploadFile(MultipartFile file){

        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        if(file == null || file.isEmpty()){
            return Result.fail().message("请选择要上传的图片");
        }
        if(file.getSize() > 1024 * 1024 * 2){
            return Result.fail().message("图片不能大于2MB");
        }
        String contentType = file.getContentType();
        if(contentType.equals("image/jpeg") || contentType.equals("image/png") || contentType.equals("image/gif") || contentType.equals("image/jpg")) {
            try {
                //创建OSSClient实例
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                //上传文件流
                InputStream inputStream = file.getInputStream();
                //获取文件名称
                String fileOriginalName = file.getOriginalFilename();
                //使用uuid在文件名称中添加唯一值
                String uuid = UUID.randomUUID().toString().replace("-", "");
                fileOriginalName = uuid + fileOriginalName;
                String datePath = new DateTime().toString("yyyy/MM/dd");
                fileOriginalName = datePath + "/" + fileOriginalName;
                //调用oss进行上传
                //第一个参数BucketName,第二个参数上传到oss文件的路径和文件名称，第三个参数文件输入流
                ossClient.putObject(bucketName, fileOriginalName, inputStream);
                //关闭OSSClient
                ossClient.shutdown();
                String url = "https://" + bucketName + "." + endpoint + "/" + fileOriginalName;
                return Result.ok(url).message("图片上传成功");
            } catch (Exception e) {
                return Result.fail().message("图片上传失败");
            }
        }else {
            return Result.fail().message("图片格式错误");
        }
    }


}
